package com.erlinyou.travel.web.controller.user;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;

public class S3Util {
	private static BasicAWSCredentials awsCreds = new BasicAWSCredentials("AKIAPEXT45ZOFVYV44WQ",
			"4nbA6DSJyLVof28WKvGoOD02o7cmAQyx66qYPDhj");

	private static com.amazonaws.regions.Regions region = com.amazonaws.regions.Regions.valueOf("CN_NORTH_1");
	private static AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
			.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion(region).build();

	private static AmazonS3 s3 = AmazonS3ClientBuilder.standard()
			.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion(region).build();

	private static final String policyStr = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"sid1\",\"Effect\":\"Allow\",\"Action\":[\"s3:Get*\",\"s3:List*\",\"s3:Put*\"],\"Resource\":[\"arn:aws-cn:s3:::bucketName/folder/userId/*\"]}]}";

	public static final String DEFAULT_BUCKET = "file.jingcailvtu.org";
	public static final String DEFAULT_FOLDER = "userinfo";
	public static final String DEFAULT_GROUP_FOLDER = "groupinfo";

	public static final String S3_HOST ="https://s3.cn-north-1.amazonaws.com.cn/";
	
	/**
	 * 获取aws临时凭证
	 * 
	 * @param userId
	 * @return
	 */
	public static Credentials getCredentials(String userId) {
		return getCredentials(DEFAULT_BUCKET, DEFAULT_FOLDER, userId);
	}

	private static Credentials getCredentials(String bucketName, String folder, String userId) {
		userId = userId.length() > 1 ? userId : "0" + userId;
		String policy = policyStr.replaceAll("bucketName", bucketName);
		policy = policy.replaceAll("folder", folder);
		policy = policy.replaceAll("userId", userId);
		GetFederationTokenRequest request = new GetFederationTokenRequest().withName(userId).withPolicy(policy)
				.withDurationSeconds(129600);// 1.5天
		GetFederationTokenResult response = client.getFederationToken(request);
		Credentials credentials = response.getCredentials();
		return credentials;
	}

	public static String uploadGroupImageToS3(String groupId,String key, BufferedImage image) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write(image, "gif", os);
		InputStream is = new ByteArrayInputStream(os.toByteArray());

		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType("image/jpeg");
	
		s3.putObject(DEFAULT_BUCKET, DEFAULT_GROUP_FOLDER+"/"+groupId+key, is, metadata);
//		https://s3.cn-north-1.amazonaws.com.cn/resource.jingcailvtu.org/1073848/userheadercrop.png
		return S3_HOST+DEFAULT_BUCKET+"/"+DEFAULT_GROUP_FOLDER+"/"+groupId+key;
	}
	/*
	 * public static void main(String[] args) throws Exception {
	 * uploadImageToS3("","test.jpg", ImageIO.read(new
	 * File("C:\\Users\\Administrator\\Desktop\\cnIT4A9508.jpg"))); }
	 */
	// private static BasicSessionCredentials sessionCredentials = new
	// BasicSessionCredentials(credentials.getAccessKeyId(),
	// credentials.getSecretAccessKey(),credentials.getSessionToken());
	//
	// private static AmazonS3 s3 = AmazonS3ClientBuilder.standard()
	// .withCredentials(new AWSStaticCredentialsProvider(sessionCredentials))
	// .withRegion(com.amazonaws.regions.Regions.valueOf("CN_NORTH_1"))
	// .build();
}
